<?php

class openapi_api_function_v1_order extends openapi_api_function_abstract implements openapi_api_function_interface{

    function __construct() {
        parent::__construct();
        $this->mCart = app::get('b2c')->model('cart');
    }

    public function add($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        if($params['virtual_cart']){
            $_POST['virtual_cart'] = $params['virtual_cart'];
        }
        if(isset($_POST['virtual_cart']) && !empty($_POST['virtual_cart'])){
            $temps = app::get('b2c')->model('orders')->getList('order_id',array('prepare_order_source'=>$_POST['virtual_cart']));
            if(count($temps)>0){
                return $this->apiData(false,null,400,app::get('b2c')->_('已经生产过订单了'));
            }
        }
        $db = kernel::database();
        $transaction_status = $db->beginTransaction();
        $arrMember = $this->get_current_member();
        $params['delivery']['ship_email'] = $arrMember['email'];
        $params['purchase']['member_id'] = $member_id;
        $params['purchase']['addr_id'] = $params['delivery']['addr_id'];
        $params['purchase']['def_area'] = $params['delivery']['region_id'];
        $params['payment']['currency'] = $params['currency'];
        $params['payment']['pay_app_id'] = $params['pay_app_id'];
        $params['split_order'] = urldecode($params['split_order']);
        $params['business_goods'] = urldecode($params['business_goods']);
        if(empty($params['shipping'])){
            return $this->apiData(false,null,400,app::get('b2c')->_('缺少运费模板数据'));
        }
        $shipping = array();
        foreach ($params['shipping'] as $s_k => $s_v) {
            $shipping[$s_v['order_split_id']][$s_v['slips_id']]['memo'] = $s_v['memo'];
            $shipping[$s_v['order_split_id']][$s_v['slips_id']]['shipping_id'] = $s_v['shipping_id'];
        }
        unset($params['shipping']);
        $params['shipping'] = $shipping;
        $this->mCart = app::get('b2c')->model('cart');
        $allCart = $this->mCart->get_objects();
        // 校验购物车是否为空，如果为空，其他的不需要检查。
        if ($this->mCart->is_empty($allCart)){
            return $this->apiData(false,null,400,app::get('b2c')->_('操作失败，购物车为空！'));
        }
        //如果商品一致，则分单信息也应该一致。
        $temp_split_order=kernel::single('b2c_cart_object_split')->split_order($this,$params['delivery']['region_id'],$allCart);
        if($allCart['json_order_split']!=$params['split_order']){
            return $this->apiData(false,null,400,app::get('b2c')->_('购物车内容发生变化，请重新结算！'));
        }
        foreach($temp_split_order as $store_id=>$sgoods){
            foreach($sgoods['slips'] as $order_sp=>$order){
                if(empty($order['shipping'])){                    
                    return $this->apiData(false,null,400,app::get('b2c')->_('存在不支持所选地区配送的商品，请从购物车删除后重新结算！'));
                }
            }
        }
        if($allCart['business_goods'] != $params['business_goods']){
            $msg = app::get('b2c')->_("订单生成失败，数据异常！");
            return $this->apiData(false,null,400,$msg);
        }
        if (!$params['delivery']['ship_area'] || !$params['delivery']['ship_addr_area'] || !$params['delivery']['ship_addr'] || !$params['delivery']['ship_name'] || (!$params['delivery']['ship_email'] && !$member_id) || (!$params['delivery']['ship_mobile'] && !$params['delivery']['ship_tel']) || !$params['payment']['pay_app_id']){
            if (!$params['delivery']['ship_area'] || !$params['delivery']['ship_addr_area']){
                $msg .= app::get('b2c')->_("收货地区不能为空！");
            }
            if (!$params['delivery']['ship_addr']){
                $msg .= app::get('b2c')->_("收货地址不能为空！");
            }
            if (!$params['delivery']['ship_name']){
                $msg .= app::get('b2c')->_("收货人姓名不能为空！");
            }
            if (!$params['delivery']['ship_email'] && !$member_id){
                $msg .= app::get('b2c')->_("邮箱不能为空，请到个人中心进行修改");
            }
            if (!$params['delivery']['ship_mobile'] && !$params['delivery']['ship_tel']){
                $msg .= app::get('b2c')->_("手机或电话必填其一！");
            }
            if (!$params['payment']['pay_app_id']){
                $msg .= app::get('b2c')->_("支付方式不能为空！");
            }
            return $this->apiData(false,null,400,$msg);
        }
        //积分抵扣处理 todo
        $this->dis_point=0;
        $this->dis_point_money=0;
        $this->point_usage=app::get('b2c')->getConf('site.point_usage');//积分用途：1：只用于兑换，2：只用于抵扣
        $this->get_policy_method=app::get('b2c')->getConf('site.get_policy.method');//是否启用积分：1：不启用，2：按订单商品总价格计算积分，3：为商品单独设置积分
        $this->site_point_deductible_value = app::get('b2c')->getConf('site.point_deductible_value'); //积分抵扣金额的比例值
        if($this->point_usage==2&& $this->get_policy_method!=1){
            $this->dis_point=$params['payment']['dis_point']?$params['payment']['dis_point']:0;
            $this->dis_point_money=$this->dis_point*$this->site_point_deductible_value;//抵扣的总金额
        }
        foreach($temp_split_order as $store_id=>$sgoods){
            foreach($sgoods['slips'] as $order_sp=>$sorder){
                //post数据
                $order = app::get('b2c')->model('orders');
                //分单后重新构建购物车数据.
                $aCart=$this->get_split_cart($allCart,$sorder,$params,$params['shipping'][$store_id][$order_sp],$store_id);
                
                $postData=$this->get_post_cart($aCart,$sorder,$params,$params['shipping'][$store_id][$order_sp]);

                //取得购物车数据对应的订单数据。
                $order_data=$this->get_order_data($aCart,$postData,$store_id,$msg,$arrMember,$order_sp);
                if(!$order_data){
                    return $this->apiData(false,null,400,$msg);
                }

                $obj_order_create = kernel::single("b2c_order_create");
                $order_id=$order_data['order_id'];//最终order_id生成
                $order_data['prepare_order_source'] = $_POST['virtual_cart'];
                if(!empty($order_data['prepare_order_source'])){     //创建上浮预售订单时，根据源订单同步状态
                    $order_data['pay_status'] = 1;//上浮订单不需要支付
                    kernel::single('b2c_order_sync')->order_sync($order_data);
                }
                $result = $obj_order_create->save($order_data, $msg);//写订单到数据库
                
                if ($result){
                    // 发票高级配置埋点
                    foreach( kernel::servicelist('invoice_setting') as $services ) {
                        if ( is_object($services) ) {
                            if ( method_exists($services, 'saveInvoiceData') ) {
                                $services->saveInvoiceData($postData['order_id'],$postData['payment']);
                            }
                        }
                    }
                }

                // 取到日志模块
                if ($arrMember['member_id']){
                    $obj_members = app::get('b2c')->model('members');
                    $arrPams = $obj_members->dump($arrMember['member_id'], '*', array(':account@pam' => array('*')));
                }

                $log_text = "";
                if ($result){
                    $log_text[] = array(
                        'txt_key'=>'订单创建成功！',
                        'data'=>array(
                        ),
                    );
                    $log_text = serialize($log_text);
                }else{
                    $log_text[] = array(
                        'txt_key'=>'订单创建失败！',
                        'data'=>array(
                        ),
                    );
                    $log_text = serialize($log_text);
                }
                $orderLog = app::get('b2c')->model("order_log");
                $sdf_order_log = array(
                    'rel_id' => $order_id,
                    'op_id' => $arrMember['member_id'],
                    'op_name' => (!$arrMember['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
                    'alttime' => time(),
                    'bill_type' => 'order',
                    'behavior' => 'creates',
                    'result' => 'SUCCESS',
                    'log_text' => $log_text,
                );

                $log_id = $orderLog->save($sdf_order_log);

                if ($result){
                    foreach(kernel::servicelist('b2c_save_post_om') as $object){
                        $object->set_arr($order_id, 'order');
                    }

                    $this->cart_model = app::get('b2c')->model('cart_objects');
                    // 设定优惠券不可以使用
                    if (isset($aCart['object']['coupon']) && $aCart['object']['coupon']){
                        $obj_coupon = kernel::single("b2c_coupon_mem");
                        foreach ($aCart['object']['coupon'] as $coupons){
                            if($coupons['used'])
                                $obj_coupon->use_c($coupons['coupon'], $arrMember['member_id']);
                        }
                        foreach ($aCart['object']['coupon'] as $ckey => $cval) {
                            if($cval['store_id'] == $store_id){
                                $this->cart_model->remove_object('coupon', $cval['obj_ident']);
                            }
                        }
                    }

                    // 订单成功后清除购物车的的信息
                    if($params['fastbuy']){
                        unset($_SESSION['S[Cart_Fastbuy]']);//立即购买后清空session,普通购买清空购物车
                    }else{
                        $this->cart_model->remove_object('goods', $Store_goods);
                    }

                    // 得到物流公司名称
                    if ($order_data['order_objects']){
                        $itemNum = 0;
                        $good_id = "";
                        $goods_name = "";
                        foreach ($order_data['order_objects'] as $arr_objects){
                            if ($arr_objects['order_items']){
                                if ($arr_objects['obj_type'] == 'goods'){
                                    $obj_goods = app::get('b2c')->model('goods');
                                    $good_id = $arr_objects['order_items'][0]['goods_id'];
                                    $obj_goods->updateRank($good_id, 'buy_count',$arr_objects['order_items'][0]['quantity']);
                                    $arr_goods = $obj_goods->dump($good_id);
                                }

                                foreach ($arr_objects['order_items'] as $arr_items){
                                    $itemNum = kernel::single('ectools_math')->number_plus(array($itemNum, $arr_items['quantity']));
                                    if ($arr_objects['obj_type'] == 'goods'){
                                        if ($arr_items['item_type'] == 'product')
                                            $goods_name .= $arr_items['name'] . ($arr_items['products']['spec_info'] ? '(' . $arr_items['products']['spec_info'] . ')' : '') . '(' . $arr_items['quantity'] . ')';
                                    }
                                }
                            }
                        }

                        $obj_dlytype = app::get('b2c')->model('dlytype');
                        $arr_dlytype = $obj_dlytype->dump($order_data['shipping']['shipping_id'], 'dt_name');
                        $arr_updates = array(
                            'order_id' => $order_id,
                            'total_amount' => $order_data['total_amount'],
                            'shipping_id' => $arr_dlytype['dt_name'],
                            'ship_mobile' => $order_data['consignee']['mobile'],
                            'ship_tel' => $order_data['consignee']['telephone'],
                            'ship_addr' => $order_data['consignee']['addr'],
                            'ship_email' => $order_data['consignee']['email'] ? $order_data['consignee']['email'] : '',
                            'ship_zip' => $order_data['consignee']['zip'],
                            'ship_name' => $order_data['consignee']['name'],
                            'member_id' => $order_data['member_id'] ? $order_data['member_id'] : 0,
                            'uname' => (!$order_data['member_id']) ? app::get('b2c')->_('顾客') : $arrPams['pam_account']['login_name'],
                            'itemnum' => count($order_data['order_objects']),
                            'goods_id' => $good_id,
                            'goods_url' => kernel::base_url(1).kernel::url_prefix().(kernel::single('site_router')->gen_url(array('app'=>'b2c','ctl'=>'site_product','act'=>'index','arg0'=>$good_id))),
                            'thumbnail_pic' => base_storager::image_path($arr_goods['image_default_id']),
                            'goods_name' => $goods_name,
                            'ship_status' => '',
                            'pay_status' => 'Nopay',
                            'is_frontend' => true,
                        );
                        $order->fireEvent('create', $arr_updates, $order_data['member_id']);
                    }

                    $db->commit($transaction_status);

                    /** 订单创建结束后执行的方法 **/
                    $odr_create_service = kernel::servicelist('b2c_order.create');
                    $arr_order_create_after = array();
                    if ($odr_create_service){
                        foreach ($odr_create_service as $odr_ser){
                            if(!is_object($odr_ser)) continue;

                            if( method_exists($odr_ser,'get_order') )
                                $index = $odr_ser->get_order();
                            else $index = 10;

                            while(true) {
                                if( !isset($arr_order_create_after[$index]) )break;
                                $index++;
                            }
                            $arr_order_create_after[$index] = $odr_ser;
                        }
                    }
                    ksort($arr_order_create_after);
                    if ($arr_order_create_after){
                        foreach ($arr_order_create_after as $obj){
                            $obj->generate($order_data);
                        }
                    }
                    /** end **/
                }else{
                    $db->rollback();
                }

                if ($result){
                    $order_num = $order->count(array('member_id' => $order_data['member_id']));
                    $obj_mem = app::get('b2c')->model('members');
                    $obj_mem->update(array('order_num'=>$order_num), array('member_id'=>$order_data['member_id']));

                    // 与中心交互
                    $is_need_rpc = false;
                    $obj_rpc_obj_rpc_request_service = kernel::servicelist('b2c.rpc_notify_request');
                    foreach ($obj_rpc_obj_rpc_request_service as $obj){
                        if ($obj && method_exists($obj, 'rpc_judge_send')){
                            if ($obj instanceof b2c_api_rpc_notify_interface)
                                $is_need_rpc = $obj->rpc_judge_send($order_data);
                        }
                        if ($is_need_rpc) break;
                    }

                    if ($is_need_rpc){
                        //新的版本控制api
                        $obj_apiv = kernel::single('b2c_apiv_exchanges_request');
                        $obj_apiv->rpc_caller_request($order_data, 'ordercreate');
                    }
                    
                    $flag = true;
                    $aOrders[] = $order_id;
                }else{
                    $flag = false;
                }
            }
        }
        if($flag){
            $orderid = current($aOrders);
            $total_price = app::get('b2c')->model('orders')->getRow('final_amount,order_type',array('order_id'=>$orderid));
            $pay_price = $total_price['final_amount'];
            if($total_price['order_type']=='preparesell'){//预售只支付预付款
                $prepare_orders = app::get('preparesell')->model('prepare_order')->getList('*',array('order_id'=>$orderid));
                $first_payment = 0;
                foreach ($prepare_orders as $key => $value) {
                    $first_payment += $value['first_payment'] * $value['itemnum'];
                }
                $pay_price = $first_payment;
            }
            $resultdata = array();
            $resultdata['orderid'] = $orderid;
            $resultdata['total_price'] = number_format($total_price['final_amount'],2);
            $resultdata['uname'] = $arrMember['uname'];
            $resultdata['order_type'] = $total_price['order_type'];
            $resultdata['pay_price'] = number_format($pay_price,2);
            return $this->apiData(true,$resultdata,200,app::get('b2c')->_("订单生成成功！"));
        }else{
            return $this->apiData(false,null,400,$msg);
        }

    }
    public function padd($params,&$code,&$sub_msg){
        $data = $params;
        $rs = kernel::single('openapi_api_router')->orderAdd($data);
        $result = array('rsp'=>'succ','data'=>array('order_bn'=>$data['content']['order_bn']));
        return $result;
    }
    public function getList ($params,&$code,&$sub_msg)
    {
    	$offset = intval($params['page_no']) > 0 ? intval($params['page_no']) : 1;
    	$limit = (intval($params['page_size']) > 100 || intval($params['page_size']) <= 0) ? 100 : intval($params['page_size']);
    	unset($params['page_no']);
    	unset($params['page_size']);
    	
    	
    	$filter = array();
    	foreach ($params as $k=>$param){
    		if(empty($param)) continue;
    		switch ($k){
    			case 'po_time':
    				$filter['purchase_time'] = $param;
    				break;
    			case 'statement_status':
    				$filter['statement'] = $param;
    				break;
    			default:
    				$filter[$k] = $param;
    				break;
    		}
    	}
    	$result = kernel::single('openapi_data_original_po')-> getList ($filter,$offset,$limit);
    
    	// todo定义返回结构
    
    
    	return $result;
    }

    /**
     * 获取支付信息
     * @param
     * @return
     * @author hmg
     **/
    public function topayment($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $order_id = $params['order_id'];
        $objOrder = app::get('b2c')->model('orders');
        $sdf = $objOrder->dump($order_id);
        $objMath = kernel::single("ectools_math");
        if(!$sdf){
            return $this->apiData(false,null,400,app::get('b2c')->_('未找到该订单'));
        }

        $sdf['total_amount'] = $sdf['cur_amount'];
        $sdf['cur_amount'] = $objMath->number_minus(array($sdf['cur_amount'], $sdf['payed']));

        //预售处理
        if($sdf['order_type']=='preparesell' && ($sdf['pay_status']=='0'||$sdf['pay_status']=='3')){
            $mdl_prepapre_order = app::get('preparesell')->model('prepare_order');
            $prepare_orders = $mdl_prepapre_order->getList('*',array('order_id'=>$sdf['order_id']));
            $tmp = array();
            $prepare_order = array();
            foreach ($prepare_orders as $key => $value) {
                $tmp[$value['product_id']] = $value;
                $prepare_order['order_id'] = $value['order_id'];
                $prepare_order['store_id'] = $value['store_id'];
                $prepare_order['member_id'] = $value['member_id'];
                $prepare_order['prepare_id'] = $value['prepare_id'];
                $prepare_order['itemnum'] = $value['itemnum'];
                $prepare_order['total_price'] += $value['preparesell_price'] * $value['itemnum'];
                $prepare_order['first_payment'] += $value['first_payment'] * $value['itemnum'];
                $prepare_order['final_payment'] += $value['final_payment'] * $value['itemnum'];;
                $prepare_order['begin_time'] = $value['begin_time'];
                $prepare_order['end_time'] = $value['end_time'];
                $prepare_order['end_time_first'] = $value['end_time_first'];
                $prepare_order['end_time_final'] = $value['end_time_final'];
                $prepare_order['pay_status'] = $value['pay_status'];
                $prepare_order['approve_status'] = $value['approve_status'];
            }
            // $this->pagedata['prepare_orders'] = $tmp;
            // $this->pagedata['prepare_order'] = $prepare_order;
            if($sdf['pay_status']=='0'){
                $sdf['cur_amount'] = $prepare_order['first_payment'];
            }else{
                $sdf['cur_amount'] = $prepare_order['final_payment'];
            }
        }
        
        $this->pagedata['order'] = $sdf;
        // 货到付款不能进入此页面
        if ($sdf['payinfo']['pay_app_id'] == '-1')
        {
            return $this->apiData(false,null,400,app::get('b2c')->_('货到付款订单无需线上支付'));
        }

        if($selecttype){
            $selecttype = 1;
        }else{
            $selecttype = 0;
        }
         //by 钟成林 如果是线下订单
        if($sdf['payinfo']['pay_app_id'] == 'offline')
        {
            $selecttype = 1;
        }

        $this->pagedata['order']['selecttype'] = $selecttype;
        $opayment = app::get('ectools')->model('payment_cfgs');
        $this->pagedata['payments'] = $opayment->getListByCode($sdf['currency']);

        $system_money_decimals = app::get('b2c')->getConf('system.money.decimals');
        $system_money_operation_carryset = app::get('b2c')->getConf('system.money.operation.carryset');
        foreach ($this->pagedata['payments'] as $key=>&$arrPayments)
        {
            if (!$sdf['member_id'])
            {
                if (trim($arrPayments['app_id']) == 'deposit')
                {
                    unset($this->pagedata['payments'][$key]);
                    continue;
                }
            }

            if ($arrPayments['app_id'] == $this->pagedata['order']['payinfo']['pay_app_id'])
            {
                $this->pagedata['order']['cur_amount'] = $arrPayments['cur_money'] = $objMath->formatNumber($this->pagedata['order']['cur_amount'], $system_money_decimals, $system_money_operation_carryset);
                $this->pagedata['order']['total_amount'] = $arrPayments['total_amount'] = $objMath->formatNumber($this->pagedata['order']['total_amount'], $system_money_decimals, $system_money_operation_carryset);
            }
            else
            {
                $arrPayments['cur_money'] = $this->pagedata['order']['cur_amount'];
                $cur_discount = $objMath->number_multiple(array($sdf['discount'], $this->pagedata['order']['cur_rate']));
                if ($this->pagedata['order']['payinfo']['cost_payment'] > 0)
                {
                    if ($this->pagedata['order']['cur_amount'] > 0)
                        $cost_payments_rate = $objMath->number_div(array($arrPayments['cur_money'], $objMath->number_plus(array($this->pagedata['order']['cur_amount'], $this->pagedata['order']['payed']))));
                    else
                        $cost_payments_rate = 0;
                    $cost_payment = $objMath->number_multiple(array($objMath->number_multiple(array($this->pagedata['order']['payinfo']['cost_payment'], $this->pagedata['order']['cur_rate'])), $cost_payments_rate));
                    $arrPayments['cur_money'] = $objMath->number_minus(array($arrPayments['cur_money'], $cur_discount));
                    $arrPayments['cur_money'] = $objMath->number_minus(array($arrPayments['cur_money'], $cost_payment));
                    $arrPayments['cur_money'] = $objMath->number_plus(array($arrPayments['cur_money'], $objMath->number_multiple(array($arrPayments['cur_money'], $arrPayments['pay_fee']))));
                    $arrPayments['cur_money'] = $objMath->number_plus(array($arrPayments['cur_money'], $cur_discount));
                }
                else
                {
                    $arrPayments['cur_money'] = $objMath->number_minus(array($arrPayments['cur_money'], $cur_discount));
                    $cost_payment = $objMath->number_multiple(array($arrPayments['cur_money'], $arrPayments['pay_fee']));
                    $arrPayments['cur_money'] = $objMath->number_plus(array($arrPayments['cur_money'], $cost_payment));
                    $arrPayments['cur_money'] = $objMath->number_plus(array($arrPayments['cur_money'], $cur_discount));
                }

                $arrPayments['total_amount'] = $objMath->formatNumber($objMath->number_div(array($arrPayments['cur_money'], $this->pagedata['order']['cur_rate'])), $system_money_decimals, $system_money_operation_carryset);
                $arrPayments['cur_money'] = $objMath->formatNumber($arrPayments['cur_money'], $system_money_decimals, $system_money_operation_carryset);
            }
        }

        $objCur = app::get('ectools')->model('currency');
        $aCur = $objCur->getFormat($this->pagedata['order']['currency']);
        $this->pagedata['order']['cur_sign'] = $aCur['sign'];

        if ($sdf['cur_amount'] == '0' && $sdf['pay_status'] == '0')
        {
            // 模拟支付流程
            $objPay = kernel::single("ectools_pay");
            $sdffds = array(
                'payment_id' => $objPay->get_payment_id(),
                'order_id' => $sdf['order_id'],
                'rel_id' => $sdf['order_id'],
                'op_id' => $sdf['member_id'],
                'pay_app_id' => $sdf['payinfo']['pay_app_id'],
                'currency' => $sdf['currency'],
                'payinfo' => array(
                    'cost_payment' => $sdf['payinfo']['cost_payment'],
                ),
                'pay_object' => 'order',
                'member_id' => $sdf['member_id'],
                'op_name' => $this->user->user_data['account']['login_name'],
                'status' => 'ready',
                'cur_money' => $sdf['cur_amount'],
                'money' => $sdf['total_amount'],
            );
            $is_payed = $objPay->gopay($sdffds, $msg);
            if (!$is_payed){
                $msg = app::get('b2c')->_('订单自动支付失败！');
                return $this->apiData(false, null, 400, $msg);
            }

            $obj_pay_lists = kernel::servicelist("order.pay_finish");
            $is_payed = false;
            foreach ($obj_pay_lists as $order_pay_service_object)
            {
                $is_payed = $order_pay_service_object->order_pay_finish($sdffds, 'succ', 'font',$msg);
            }
        }
        //平台客服
        $qq=app::get('b2c')->getConf('member.ServiceQQ');
        $this->pagedata['qq']=$qq;
        $tel=app::get('b2c')->getConf('member.ServiceTel');
        $this->pagedata['tel']=$tel;
        //begin 获取银行信息
        $bankInfo = kernel::single('b2c_banks_info')->getBank();
        $this->pagedata['bankinfo'] = $bankInfo;

        $is_seller_ornot=$this->get_current_member();
        $this->pagedata['myadvance'] = $is_seller_ornot['advance'];
        $this->pagedata['my_credit'] = app::get('business')->model('storemanger_oncredit')->getMyCredit($is_seller_ornot['member_id']);
        $this->pagedata['is_seller_ornot'] = $is_seller_ornot['seller'];
        
        return $this->apiData(true,$this->pagedata,200);

    }

    /**
     * 订单支付
     **/
    public function dopayment($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $arrMember = $this->get_current_member();
        $objOrders = app::get('b2c')->model('orders');
        $objPay = kernel::single('ectools_pay');
        $objMath = kernel::single('ectools_math');
        // 得到商店名称
        $shopName = app::get('b2c')->getConf('system.shopname');
        // Post payment information.
        $sdf['order_id'] = $params['order_id'];
        $sdf['money'] = $params['money'];
        $sdf['cur_money'] = $params['money'];
        $sdf['cur_amount'] = $params['money'];
        $sdf['pay_password'] = $params['pay_password'];
        $pay_object = 'order';
        /*验证支付密码*/
        if(md5($sdf['pay_password']) !== $arrMember['pay_password'] && $pay_object!= 'recharge'){
            return $this->apiData(false,null,400,app::get('b2c')->_('支付密码错误'));
        }
        $sdf['money'] = floatval($sdf['money']);
        //ajx 防止恶意修改支付金额，导致支付状态异常
        $orders = $objOrders->dump($sdf['order_id']);
        $sdf['cur_amount'] = $objMath->number_minus(array($orders['cur_amount'], $orders['payed']));
        $orders['total_amount'] = $objMath->number_div(array($orders['cur_amount'], $orders['cur_rate']));
        $sdf['money'] = floatval($orders['total_amount'] - $orders['payed']);
        $sdf['currency']=$orders['currency'];
        $sdf['cur_money'] = $objMath->number_minus(array($orders['cur_amount'], $orders['payed']));
        $sdf['cur_rate'] = $orders['cur_rate'];
        $sdf['pay_app_id'] = $orders['payinfo']['pay_app_id'];
        $sdf['store_id'] = $orders['store_id'];

        $payment_id = $sdf['payment_id'] = $objPay->get_payment_id();
        if ($arrMember){
            $sdf['member_id'] = $arrMember['member_id'];
        }
        $sdf['pay_object'] = $pay_object;
        $sdf['shopName'] = $shopName;
        $arrOrders = $orders;

        // 检查是否能够支付
        $obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));

        //预售处理
        if($orders['order_type']=='preparesell' && !empty($orders['prepare_order_source']) && $orders['prepare_order_source']!='0'){
            return $this->apiData(false,null,400,app::get('b2c')->_('预售上浮订单无需支付'));
        }

        if($orders['order_type']=='preparesell' && $orders['pay_status'] == '0'){
            $mdl_prepapre_order = app::get('preparesell')->model('prepare_order');
            $prepare_orders = $mdl_prepapre_order->getList('*',array('order_id'=>$orders['order_id']));
            $tmp = array();
            $prepare_order = array();
            foreach ($prepare_orders as $key => $value) {
                $tmp[$value['product_id']] = $value;
                $prepare_order['order_id'] = $value['order_id'];
                $prepare_order['store_id'] = $value['store_id'];
                $prepare_order['member_id'] = $value['member_id'];
                $prepare_order['prepare_id'] = $value['prepare_id'];
                $prepare_order['itemnum'] = $value['itemnum'];
                $prepare_order['total_price'] += $value['preparesell_price'] * $value['itemnum'];
                $prepare_order['first_payment'] += $value['first_payment'] * $value['itemnum'];
                $prepare_order['final_payment'] += $value['final_payment'] * $value['itemnum'];;
                $prepare_order['status'] = $value['status'];
                $prepare_order['begin_time'] = $value['begin_time'];
                $prepare_order['end_time'] = $value['end_time'];
                $prepare_order['begin_time_final'] = $value['begin_time_final'];
                $prepare_order['end_time_final'] = $value['end_time_final'];
                $prepare_order['pay_status'] = $value['pay_status'];
            }
            $orders['cur_amount'] = $prepare_order['first_payment'];
        }

        $sdf['cur_amount'] = $objMath->number_minus(array($orders['cur_amount'], $orders['payed']));
        $orders['total_amount'] = $objMath->number_div(array($orders['cur_amount'], $orders['cur_rate']));
        $sdf['money'] = floatval($orders['total_amount'] - $orders['payed']);
        $sdf['currency']=$orders['currency'];
        $sdf['cur_money'] = $objMath->number_minus(array($orders['cur_amount'], $orders['payed']));
        $sdf['cur_rate'] = $orders['cur_rate'];
        //原选择的支付方式（支付宝）有手续费，再选择其他无手续费的支付方式，post数据中含有手续费 Add by PanF   2014-06-25 end

        //缺少的数据
        $aCur = app::get('ectools')->model('currency')->getFormat($orders['currency']);
        $sdf['cur_def'] = $aCur['sign'];
        $sdf['cost_payment'] = $orders['payinfo']['cost_payment'];
        $sdf['memo'] = $orders['memo'];
        //下面的数据不知何用
        $sdf['bankaccounttype'] = '92';
        $sdf['banktype'] = '9001000';
        $sdf['olepayment'] = 'deposit';

        $sdf_post = $sdf;
        $sdf_post['money'] = $sdf['cur_money']; 
        if (!$obj_checkorder->check_order_pay($sdf['order_id'],$sdf_post,$message))
        {
            return $this->apiData(false,null,400,$message);
        }

        if (!$sdf['pay_app_id'])
            $sdf['pay_app_id'] = $arrOrders['payinfo']['pay_app_id'];

        $sdf['currency'] = $arrOrders['currency'];
        $sdf['total_amount'] = $arrOrders['total_amount'];
        $sdf['payed'] = $arrOrders['payed'] ? $arrOrders['payed'] : '0.000';
        $sdf['money'] = $objMath->number_div(array($sdf['cur_money'], $arrOrders['cur_rate']));

        $sdf['payinfo']['cost_payment'] = $arrOrders['payinfo']['cost_payment'];

        // 相关联的id.
        $sdf['rel_id'] = $sdf['order_id'];
        $sdf['status'] = 'ready';
        // 需要加入service给其他实体和虚拟卡
        $obj_prepaid = kernel::service('b2c.prepaidcards.add');
         
        $is_save_prepaid = false;
        if ($obj_prepaid)
        {
            $is_save_prepaid = $obj_prepaid->gen_charge_log($sdf);
        }
        $is_payed = $objPay->generate($sdf,$this, $msg);
        //$is_payed = true;
        
        if ($is_save_prepaid && $is_payed)
        {
            $obj_prepaid->update_charge_log($sdf);
        }

        if ($sdf['pay_app_id'] == 'deposit')
        {
            // 预存款支付
            if ($is_payed){ 
                //预售订单同步
                if(isset($prepare_order['order_id'])){
                    $prepare_order['pay_status']++;
                    $mdl_prepapre_order = app::get('preparesell')->model('prepare_order');
                    $sql = "UPDATE sdb_preparesell_prepare_order SET pay_status='".intval($prepare_order['pay_status'])."' where order_id='".$prepare_order['order_id']."'";
                    $mdl_prepapre_order->db->exec($sql);
                    $update_order = $objOrders->getRow('*',array('order_id'=>$prepare_order['order_id']));
                    kernel::single('b2c_order_sync')->order_sync($update_order);
                }elseif ($orders['order_type']=='preparesell' && $orders['pay_status'] == '3') {
                    $mdl_prepapre_order = app::get('preparesell')->model('prepare_order');
                    $sql = "UPDATE sdb_preparesell_prepare_order SET pay_status='3' where order_id='".$orders['order_id']."'";
                    $mdl_prepapre_order->db->exec($sql);
                    $update_order = $objOrders->getRow('*',array('order_id'=>$orders['order_id']));
                    kernel::single('b2c_order_sync')->order_sync($update_order);
                }

                // 通知商家
                if(in_array($sdf['store_id'], kernel::single('b2c_goods_store')->hqStoreId())){
                    $data['to_id'] = '1';
                    $data['msg_to'] = app::get('b2c')->_('管理员');
                }else{
                    $sql = 'select a.login_name,a.account_id from sdb_business_storemanger m,sdb_pam_account a where m.account_id=a.account_id and m.store_id='.$sdf['store_id'];
                    $seller = kernel::database()->select($sql);
                    $data['to_id'] = $seller[0]['account_id'];
                    $data['msg_to'] = $seller[0]['login_name'];
                }
                $buyer = app::get('pam')->model('account')->dump($sdf['member_id'], 'login_name');
                $data['subject'] = app::get('b2c')->_('买家已付款');
                $data['comment'] = app::get('b2c')->_('订单号：').$sdf['order_id'];
                $data['order_id'] = $sdf['order_id'];
                $data['has_sent'] = 'true';
                $data['member_id'] = $sdf['member_id'];
                $data['uname'] = $buyer['login_name'];
                $data['deal_type'] = '2';
                kernel::single('b2c_message_msg')->send($data);

                return $this->apiData(true,null,200,app::get('b2c')->_('支付成功！'));
            }else{
                return $this->apiData(false,null,400,$msg);
            }
        }
    }

    //取得订单数据。
    function get_order_data($aCart,$postData,$store_id,&$msg,$arrMember,$order_sp){
        $db = kernel::database();
        $obj_filter = kernel::single('b2c_site_filter');
        $postData = $obj_filter->check_input($postData);

        $order = app::get('b2c')->model('orders');
        $postData['order_id'] = $order_id = $order->gen_id();
        $postData['member_id'] = $arrMember['member_id'] ? $arrMember['member_id'] : 0;
        $order_data = array();
        
        $obj_order_create = kernel::single("b2c_order_create");
        // 加入订单能否生成的判断
        $obj_checkorder = kernel::service('b2c_order_apps', array('content_path'=>'b2c_order_checkorder'));
        if ($obj_checkorder){
            if (!$obj_checkorder->check_create($aCart, $postData['delivery']['ship_area'], $message)){
                $msg = $message;echo 1;
                return false;
            }
        }

        $order_data = $obj_order_create->generate($postData,'',$msg,$aCart,$store_id,$order_sp);
        if(!$order_data){
            return false;
        }
        $order_data['store_id'] = $store_id;
        $obj_checkproducts = kernel::servicelist('b2c_order_check_products');
        if ($obj_checkproducts){
            foreach($obj_checkproducts as $obj_check){
                if (!$obj_check->check_products($order_data, $messages)){
                    $msg = $message;echo 2;
                    return false;
                }
            }
        }

        if (!$order_data || !$order_data['order_objects']){
            $db->rollback();
            $msg = $message;echo 3;
            return false;   
        }

        if($order_data['shipping']['shipping_id'] == null || $order_data['shipping']['shipping_id'] == ''){
            $msg = app::get('b2c')->_("请选择经销商配送方式！");echo 4;
            return false;
        }
        return $order_data;
    }

    //为分单准备post数据。积分抵扣
    function get_post_cart($aCart,$sOrder,$postData,$oShipping){
        $post=array();
        if(isset($postData['purchase'])){
            $post['purchase']=$postData['purchase'];
        }
        if(isset($postData['extends_args'])){
            $post['extends_args']=$postData['extends_args'];
        }
        if(isset($postData['delivery'])){
            $post['delivery']=$postData['delivery'];
        }
        if(isset($postData['payment'])){
            $post['payment']=$postData['payment'];
        }
        if(isset($postData['fromCart'])){
            $post['fromCart']=$postData['fromCart'];
        }
        if(isset($postData['split_order'])){
            $post['split_order']=$postData['split_order'];
        }
        if(isset($postData['minfo'])){
            $post['minfo']=$postData['minfo'];
        }
        $shipping_id = $oShipping['shipping_id'];
        $post['delivery']['shipping_id'] = $shipping_id;
        $post['delivery']['is_protect'][$shipping_id] = $oShipping['is_protect'];
        $post['is_protect'][]= $oShipping['is_protect'];
        $post['shipping_id'][]= $oShipping['shipping_id'];
        $post['memo'] = $oShipping['memo'];
        $post['payment']['dis_point']=0;
        // 保价费
        // $cost_protect=0;
        // if($oShipping['is_protect']){
        //     $cost_protect+=$sOrder['shipping'][$oShipping['shipping_id']]['protect_money'];                
        // }
        if($this->point_usage==2&& $this->get_policy_method!=1){
            if($this->dis_point>0 && $this->site_point_deductible_value>0 &&$this->dis_point_money>0){
                //订单金额。
                $subtotal=$aCart['subtotal'] - $aCart['subtotal_discount'];//+$cost_protect;
                
                if($subtotal>$this->dis_point_money){//订单余额满足积分抵扣金额。
                    $post['payment']['dis_point']=$this->dis_point;
                    $this->dis_point=0;
                }else{
                    $tdis_point_money=$subtotal;
                    //根据抵扣钱数重新计算抵扣积分。
                    $post['payment']['dis_point']=$tdis_point_money/$this->site_point_deductible_value;
                    $this->dis_point-=$post['payment']['dis_point'];
                    $this->dis_point_money-=$tdis_point_money;
                }
            }
        }
        return $post;
    }

    //根据分单数据重新构建购物车结构，以便直接生成订单结构。
    function get_split_cart(&$allCart,$sOrder,$postData,$oShipping,$store_id){
        $sCart=array();        
        foreach($sOrder['object'] as $obj_type=>$obj){
           foreach($obj['index'] as $index){
                $sCart['object'][$obj_type][]=$allCart['object'][$obj_type][$index];
           }
        }

        $this->mCart->count_objects($sCart);

        if($allCart['promotion']){
            foreach($allCart['promotion'] as $pkey=> $promotion){
                foreach($promotion as $ptypekey=> $pcoupon){
                    if($allCart['is_free_shipping'][$store_id]){//免运费
                        if($pcoupon['store_id']==$store_id){
                            $sCart['promotion'][$pkey][$ptypekey]=$pcoupon;
                        }                              
                    }elseif ($pkey == 'coupon'){
                        $sCart['promotion'][$pkey][$ptypekey] = $pcoupon;
                    }else{//折扣或者送优惠券
                        if($pcoupon['store_id']==$store_id){
                            if($pcoupon['discount_amount']>0){                                   
                               if($sCart['subtotal']>$pcoupon['discount_amount']){
                                    $sCart['discount_amount']=$pcoupon['discount_amount'] + $sCart['discount_amount_prefilter'];
                                    $sCart['subtotal_discount']=$pcoupon['discount_amount'] + $sCart['discount_amount_prefilter'];
                                    $sCart['discount_amount_order']=$pcoupon['discount_amount'];
                                    $allCart['promotion'][$pkey][$ptypekey]=$pcoupon['discount_amount']-$sCart['subtotal'];
                               }
                               $sCart['promotion'][$pkey][$ptypekey]=$pcoupon;
                            }else if($pcoupon['discount_amount']==0){//送优惠券。
                               $sCart['promotion'][$pkey][$ptypekey]=$pcoupon;
                               unset($allCart['promotion'][$pkey][$ptypekey]);
                            }
                        }
                    }
                }
            }
        }

        if($allCart['object']['coupon']){
           foreach($allCart['object']['coupon'] as $coupon){
               if($coupon['store_id']==$store_id){
                    $sCart['object']['coupon'][]=$coupon;
               }
           }
        }

        if($allCart['is_free_shipping']){
            $sCart['is_free_shipping']=$allCart['is_free_shipping'][$store_id];
        }
        if($allCart['free_shipping_rule_type']){
            $sCart['free_shipping_rule_type']=$allCart['free_shipping_rule_type'][$store_id];
        }
        if($allCart['free_shipping_rule_id']){
            $sCart['free_shipping_rule_id']=$allCart['free_shipping_rule_id'][$store_id];
        }        
        if(isset($allCart['inAct'])){
           $sCart['inAct']=$allCart['inAct'];
        }
        if(isset($allCart['prepare'])){
           $sCart['prepare']=$allCart['prepare'];
        }

        if(isset($allCart['promotion_order_create'])){
            foreach($allCart['promotion_order_create'] as $key=>$promotion_order_create){
                foreach($promotion_order_create as $k=>$val){
                    $objCoupon = app::get('b2c')->model('coupons');
                    $cList = $objCoupon->dump($val['cpns_id'][0]);
                    $cList['store_id'] = explode(',',$cList['store_id']);
                    if($cList['store_id'][1]==$store_id){
                        $sCart['promotion_order_create'][$key][$k] = $val;
                    }
                }
            }
        }

        return $sCart;
    }

    /**
    * 订单列表接口
    *
    **/
    public function orderlist($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        if(!empty($params['store_id'])){
            $store = app::get('business')->model('storemanger')->getRow("account_id",array('store_id'=>$params['store_id']));
            if(!empty($store)){
                $member_id = $store['account_id'];
                $params['ordertype'] = empty($params['ordertype'])?'onpurchase':$params['ordertype'];
            }
        }
        $type = empty($params['ordertype'])?'nopayed':$params['ordertype'];
        $order_id = $params['order_id'];
        $goods_name = $params['goods_name'];
        $goods_bn = $params['goods_bn'];
        $time = $params['time'];
        $nPage = empty($params['page_no'])?1:$params['page_no'];
        $order_type = $params['order_type'];

        $order = app::get('b2c')->model('orders');
        $ctl   = kernel::single('b2c_api_site_member',$member_id);
        
        $order_id = trim($order_id);
        $goods_name = trim($goods_name);
        $goods_bn = trim($goods_bn);

        $sql = $ctl->get_search_order_ids($type,$time,$order_type);
        $arrayorser = $order->db->select($sql);
        $arr = array();
        if(empty($order_id) && empty($goods_name) && empty($goods_bn)){
            $arr = $arrayorser;
        }else{
            $search_order=$ctl->search_order($order_id,$goods_name,$goods_bn);
            foreach($arrayorser as $key=>$value){
                foreach($search_order as $k=>$v){
                    if($value['order_id']==$v['order_id']){
                        $arr[]=$value;
                    }
                }
            }
        }
        $arrayorser=$arr;
        if(empty($arrayorser)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有找到相应的订单！'));
        }else{
            $aData = $order->fetchByMember($member_id,$nPage-1,'','',$arrayorser);
        }
        $ctl->get_order_details($aData,'member_orders');
        $oImage = app::get('image')->model('image');
        $imageDefault = app::get('image')->getConf('image.set');
        $applySObj = app::get('spike')->model('spikeapply');
        $applyGObj = app::get('groupbuy')->model('groupapply');
        $applyScoreObj = app::get('scorebuy')->model('scoreapply');
        
        foreach($aData['data'] as $k=>$v) {
            //获取订单支付时间
            $obj_payment = app::get('ectools')->model('refunds');
            $payment_id = $obj_payment->get_payment($v['order_id']);
            $pay_time = app::get('ectools')->model('payments')->getRow('t_payed',array('payment_id'=>$payment_id['bill_id']));
            $aData['data'][$k]['pay_time'] = $pay_time['t_payed'];
            $obj_aftersales = app::get('aftersales')->model('return_product');
            $ord_id = $obj_aftersales->getRow('return_id',array('order_id'=>$v['order_id'],'status'=>'3','refund_type'=>'2'));
            if($ord_id){
                $aData['data'][$k]['need_send'] = 1;  // 需要退款
            }else{
                $aData['data'][$k]['need_send'] = 0;
            }
            $ord_id = $obj_aftersales->getRow('return_id',array('order_id'=>$v['order_id'],'status'=>'11','refund_type'=>'2'));
            if($ord_id){
                $aData['data'][$k]['need_edit'] = 1;  // 需要修改退货单
            }else{
                $aData['data'][$k]['need_edit'] = 0;
            }
            //预售截止支付时间
            if($v['order_type']=='preparesell'){
                $pre_order = app::get('preparesell')->model('prepare_order')->getList('*',array('order_id'=>$v['order_id']));
                $preinfo = app::get('preparesell')->model('preparesell')->getList("*",array('prepare_id'=>$pre_order[0]['prepare_id']));
                $aData['data'][$k]['prepare_info'] = array(
                    'begin_time'=>$preinfo[0]['begin_time'],//活动开始时间
                    'end_time'=>$preinfo[0]['end_time'],//活动结束时间
                    'end_time_first'=>$preinfo[0]['end_time_first'],//活动预付款支付结束时间
                    'end_time_final'=>$preinfo[0]['end_time_final'],//尾款支付结束时间
                    'order_timeout'=>$v['createtime'] + $preinfo[0]['timeout']*3600,//此订单最晚支付时间
                    'preparesell_price'=>$pre_order[0]['preparesell_price'],//预售价格
                    'first_payment'=>$pre_order[0]['first_payment'],//定金金额
                    'final_payment'=>$pre_order[0]['final_payment'],//尾款
                    'pay_status'=>$pre_order[0]['pay_status'],//支付状态 1、未支付 2、定金 3、尾款完成
                );
            }
            //end
            foreach ($v['order_objects'] as $ok => $ov) {
                foreach ($ov['order_items'] as $ok2 => $ov2) {
                    $aData['data'][$k]['goods_items'][$ok]['product']['sendnum'] += $ov2['sendnum'];
                    $aData['data'][$k]['goods_items'][$ok]['product']['receiptnum'] += $ov2['receiptnum'];
                }
            }
            foreach($v['goods_items'] as $k2=>$v2) {
                if( !$v2['product']['thumbnail_pic'] && !$oImage->getList("image_id",array('image_id'=>$v['image_default_id']))){
                    $aData['data'][$k]['goods_items'][$k2]['product']['thumbnail_pic'] = $imageDefault['S']['default_image'];
                }
                $thumbnail_pic_url = kernel::single('openapi_utils_image')->getimgbyid($aData['data'][$k]['goods_items'][$k2]['product']['thumbnail_pic']);
                $aData['data'][$k]['goods_items'][$k2]['product']['thumbnail_pic'] = $thumbnail_pic_url['url'];
                $act_id = '';
                //秒杀详细页参数
                switch($v['order_type']){
                    case 'spike':
                        $act_id = $applySObj->getOnActIdByGoodsId($v2['product']['goods_id']);
                        break;
                    case 'group':
                        $act_id = $applyGObj->getOnActIdByGoodsId($v2['product']['goods_id']);
                        break;
                    case 'score':
                        $act_id = $applyScoreObj->getOnActIdByGoodsId($v2['product']['goods_id']);
                        break;
                    case 'normal':
                        break;
                }
                
                if($act_id){
                    $aData['data'][$k]['goods_items'][$k2]['product']['args'] = array($v2['product']['goods_id'],'','',$act_id);
                }
            }

            //获取买家/卖家
            $obj_members = app::get('pam')->model('account');
            $buy_name = $obj_members->getRow('login_name',array('account_id'=>$v['member_id']));
            $aData['data'][$k]['buy_name'] = $buy_name['login_name'];

            $obj_strman = app::get('business')->model('storemanger');
            $seller_id = $obj_strman->getRow('account_id,store_idcardname,store_name',array('store_id'=>$v['store_id']));
            $aData['data'][$k]['seller_name'] = $seller_id['store_name'];
            $aData['data'][$k]['seller_real_name'] = $seller_id['store_idcardname'];
        }

        //添加订单html埋点
        // foreach($aData['data'] as $k=>$v){
        //     foreach(kernel::servicelist('business.member_orders') as $service){
        //         if(is_object($service)){
        //             if(method_exists($service,'get_orders_html')){
        //                 $aData['data'][$k]['html'] .= $service->get_orders_html($v, 'business');
        //             }
        //         }
        //     }
        // }
        $result = array();
        foreach ($aData['data'] as $key => $order) {
            $or = array();
            $or['order_id'] = $order['order_id'];
            $or['total_amount'] = $order['total_amount'];
            $or['discount_value'] = $order['discount_value'];
            $or['cur_amount'] = $order['cur_amount'];
            $or['pay_status'] = $order['pay_status'];
            $or['ship_status'] = $order['ship_status'];
            $or['is_delivery'] = $order['is_delivery'];
            $or['createtime'] = $order['createtime'];
            $or['last_modified'] = $order['last_modified'];
            $or['shipping'] = $order['shipping'];
            $or['status'] = $order['status'];
            $or['refund_status'] = $order['refund_status'];
            $or['is_extend'] = $order['is_extend'];
            $or['confirm'] = $order['confirm'];
            $or['weight'] = $order['weight'];
            $or['itemnum'] = $order['itemnum'];
            $or['pmt_goods'] = $order['pmt_goods'];
            $or['pmt_order'] = $order['pmt_order'];
            $or['payed'] = $order['payed'];
            $or['pay_time'] = $order['pay_time'];
            $or['need_send'] = $order['need_send'];
            $or['need_edit'] = $order['need_edit'];
            $or['seller_name'] = $order['seller_name'];
            $or['order_type'] = $order['order_type'];
            switch ($order['order_type']) {//用来显示，根据国家切换语言
                case 'preparesell':
                    $or['promotion_type'] = 'prepare';
                    break;
                //...
                default:
                    $or['promotion_type'] = '';
                    break;
            }
            if($order['order_type']=='preparesell'){
                $or['promotion_info'] = $order['prepare_info'];
            }
            $or['goods_items'] = array_merge($order['goods_items']);
            $data['order_id'] = $order['order_id'];
            $data['member_id'] = $member_id;
            $btnlist = $ctl->get_current_btn($data);
            $or['btnlist'] = $btnlist;
            $result[] = $or;
        }
        if(count($result)==0){
            return $this->apiData(false,null,404,app::get('b2c')->_('没有更多了'));
        }
        
        return $this->apiData(true,array('orders'=>$result,'type'=>$type,'page_no'=>$nPage),200);
    }

    /**
    * 订单详情接口
    *
    **/
    public function orderdetail($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        $params['member_id'] = $member_id;
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $order = app::get('b2c')->model('orders');
        $ctl   = kernel::single('b2c_api_site_member',$member_id);
        $aData = $order->fetchByMember($member_id,'','','',array(array('order_id'=>$params['order_id'])));
        $ctl->get_order_details($aData,'member_orders');

        $memberobj = kernel::single('b2c_api_site_member',$member_id);
        $res = $memberobj->orderdetail($params['order_id'],$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        //预售订单信息
        switch ($res['order']['order_type']) {//用来显示，根据国家切换语言
            case 'preparesell':
                $res['order']['promotion_type'] = 'prepare';
                break;
            
            default:
                
                break;
        }
        if($res['order']['order_type'] == 'preparesell'){
            $pre_order = app::get('preparesell')->model('prepare_order')->getList('*',array('order_id'=>$res['order']['order_id']));
            $preinfo = app::get('preparesell')->model('preparesell')->getList("*",array('prepare_id'=>$pre_order[0]['prepare_id']));
            $res['order']['promotion_info'] = array(
                'begin_time'=>$preinfo[0]['begin_time'],//活动开始时间
                'end_time'=>$preinfo[0]['end_time'],//活动结束时间
                'end_time_first'=>$preinfo[0]['end_time_first'],//活动预付款支付结束时间
                'end_time_final'=>$preinfo[0]['end_time_final'],//尾款支付结束时间
                'order_timeout'=>$res['order']['createtime'] + $preinfo[0]['timeout']*3600,//此订单最晚支付时间
                'preparesell_price'=>$pre_order[0]['preparesell_price'],//预售价格
                'first_payment'=>$pre_order[0]['first_payment'],//定金金额
                'final_payment'=>$pre_order[0]['final_payment'],//尾款
                'pay_status'=>$pre_order[0]['pay_status'],//支付状态 1、未支付 2、定金 3、尾款完成
            );
        }
        unset($res['request_url']);
        unset($res['order_chgpointmoney']);
        unset($res['discount_html']);
        unset($res['order']['title']);
        unset($res['order']['order_objects']);
        unset($res['order']['receiver']);
        unset($res['res_url']);
        unset($res['paymentlists']);
        $res['order']['goods_items'] = array_merge($res['order']['goods_items']);
        $res['order']['btnlist'] = kernel::single('b2c_api_site_member',$member_id)->get_current_btn($params);
        foreach ($res['order']['goods_items'] as $key => &$product) {
            $product['product']['thumbnail_pic'] = kernel::single('base_storager')->image_path($product['product']['thumbnail_pic'],'s');
        }
        foreach ($aData['data'][0]['order_objects'] as $ak=>$av) {
            $i = 0;
            foreach ($av['order_items'] as $ak2 => $av2) {
                $res['order']['goods_items'][$i]['product']['sendnum'] += $av2['sendnum'];
                $res['order']['goods_items'][$i]['product']['receiptnum'] += $av2['receiptnum'];
                $i++;
            }
        }
        //预售订单确认状况
        if($res['order']['order_type']=='preparesell'){
            $sql = "select pay_status,approve_status from sdb_preparesell_prepare_order where order_id=".$res['order']['order_id']." and member_id=".$member_id;
            $pay_status = kernel::database()->select($sql);
            $res['approve_status'] = $pay_status[0]['approve_status'];
            if($res['order']['prepare_order_source']){//上浮订单不需要支付
                $res['order']['pay_status'] = 1;
            }
        }
        foreach ($res['orderlogs'] as $key => &$log) {
            $log['log_text'] = strip_tags($log['log_text']);
            $log['addon'] = urlencode($log['addon']);
        }
        return $this->apiData(true,$res,200);
    }

    public function docancel($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $memberobj = kernel::single('b2c_api_site_member',$member_id);
        $res = $memberobj->docancel($params,$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        return $this->apiData(true,null,200,$res);
    }

    public function remind($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $memberobj = kernel::single('b2c_api_site_member',$member_id);
        $res = $memberobj->remind($params,$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        return $this->apiData(true,null,200,$err_msg);
    }

    /**
     * 部分收货
     * @param
     * @return
     * @author hmg
     **/
    public function part_receipt($params,&$code,&$sub_msg)
    {   
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->part_receipt($params,$err_msg);
        if($res){
            return $this->apiData(true,null,200,app::get('b2c')->_($err_msg));
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_($err_msg));
        }
    }

    public function gofinish($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        // 验证支付密码
        $advance_password = md5($params['pay_password']);
        $pay_password = app::get('b2c')->model('members')->getRow('pay_password',array('member_id'=>$member_id));
        $myoutpassword = $pay_password['pay_password'];//得到我的支付密码
        if(empty($myoutpassword)){
            return $this->apiData(false,null,400,app::get('b2c')->_('请先设置支付密码'));
        }
        if($advance_password!=$myoutpassword){
            return $this->apiData(false,null,400,app::get('b2c')->_('支付密码不正确'));
        }
        $order = app::get('b2c')->model('orders')->getRow('ship_status',array('order_id'=>$params['order_id']));
        if($order['ship_status']=='1'){
            $res = kernel::single('b2c_api_site_member',$member_id)->gofinish($params,$err_msg);
        }else{
            $res = kernel::single('b2c_api_site_member',$member_id)->part_receipt($params,$err_msg);
        }
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        return $this->apiData(true,null,200,$err_msg);
    }

    public function todiscuss($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $memberobj = kernel::single('b2c_api_site_member',$member_id);
        $res = kernel::single('b2c_api_site_member',$member_id)->discuss($params['order_id'],$aData,$err_msg);
        foreach ($aData['order_info'][0]['order']['goods'] as $k => &$v) {
            $v['thumbnail_pic'] = kernel::single('base_storager')->image_path($v['image_default_id'],'s');
        }
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        if(empty($aData['order_info'][0]['order']['goods'][0]['goods_id'])){
            return $this->apiData(false,null,400,app::get('b2c')->_('商品已下架或不存在'));
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200);

    }

    public function dodiscuss($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $memberobj = kernel::single('b2c_api_site_member',$member_id);
        $res = $memberobj->dodiscuss('discuss',$params['content'],$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($aData),200,app::get('b2c')->_('评论成功'));
    }

    public function extend_finish_apl($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $res = kernel::single('b2c_api_site_member',$member_id)->extend_finish_apl($params['order_id'],$err_msg);
        if(!$res){
            return $this->apiData(false,null,400,$err_msg);
        }
        return $this->apiData(true,null,200,$res);
    }

    public function torefund($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $order_id = $params['order_id'];
        $objOrder = app::get('b2c')->model('orders');
        $subsdf = array('order_objects'=>array('*',array('order_items'=>array('*',array(':products'=>'*')))));
        $result['order'] = $objOrder->dump($order_id, '*', $subsdf);
        // 校验订单的会员有效性.
        $is_verified = kernel::single('b2c_api_site_member',$member_id)->_check_verify_member($result['order']['member_id']);

        // 校验订单的有效性.
        if (!$is_verified)
        {
            return $this->apiData(false,null,400,app::get('b2c')->_('订单无效！'));
        }

        $result['orderlogs'] = $objOrder->getOrderLogList($order_id);

        if(!$result['order'])
        {
            return $this->apiData(false,null,400,app::get('b2c')->_('订单无效！'));
        }
        
        $point_money_value = app::get('b2c')->getConf('site.point_money_value');

        if($result['order']['discount_value'] > 0){
            $result['gorefund_price'] = $result['order']['payed']+($result['order']['discount_value']);
        }else{
            $result['gorefund_price'] = $result['order']['payed'];
        }
        $order_items = array();
        // 所有的goods type 处理的服务的初始化.
        $arr_service_goods_type_obj = array();
        $arr_service_goods_type = kernel::servicelist('order_goodstype_operation');
        foreach ($arr_service_goods_type as $obj_service_goods_type)
        {
            $goods_types = $obj_service_goods_type->get_goods_type();
            $arr_service_goods_type_obj[$goods_types] = $obj_service_goods_type;
        }

        $objMath = kernel::single("ectools_math");
        foreach ($result['order']['order_objects'] as $k=>$arrOdr_object)
        {
            $index = 0;
            $index_adj = 0;
            $index_gift = 0;
            $tmp_array = array();
            if($arrOdr_object['obj_type'] == 'timedbuy'){
                $arrOdr_object['obj_type'] = 'goods';
            }
            if ($arrOdr_object['obj_type'] == 'goods')
            {
                foreach($arrOdr_object['order_items'] as $key => $item)
                {
                    if ($item['item_type'] == 'product')
                        $item['item_type'] = 'goods';

                    if ($tmp_array = $arr_service_goods_type_obj[$item['item_type']]->get_aftersales_order_info($item)){
                        $tmp_array = (array)$tmp_array;
                        if (!$tmp_array) continue;
                        
                        $product_id = $tmp_array['products']['product_id'];
                        if (!$order_items[$product_id]){
                            $order_items[$product_id] = $tmp_array;
                        }else{
                            $order_items[$product_id]['sendnum'] = floatval($objMath->number_plus(array($order_items[$product_id]['sendnum'],$tmp_array['sendnum'])));
                            $order_items[$product_id]['quantity'] = floatval($objMath->number_plus(array($order_items[$product_id]['quantity'],$tmp_array['quantity'])));
                        }
                    }
                }
            }
            else
            {
                if ($tmp_array = $arr_service_goods_type_obj[$arrOdr_object['obj_type']]->get_aftersales_order_info($arrOdr_object))
                {
                    $tmp_array = (array)$tmp_array;
                    if (!$tmp_array) continue;
                    foreach ($tmp_array as $tmp){
                        if (!$order_items[$tmp['product_id']]){
                            $order_items[$tmp['product_id']] = $tmp;
                        }else{
                            $order_items[$tmp['product_id']]['sendnum'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['sendnum'],$tmp['sendnum'])));
                            $order_items[$tmp['product_id']]['nums'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['nums'],$tmp['nums'])));
                            $order_items[$tmp['product_id']]['quantity'] = floatval($objMath->number_plus(array($order_items[$tmp['product_id']]['quantity'],$tmp['quantity'])));
                        }
                    }
                }
            }
        }

        $result['order_id'] = $order_id;
        $result['order']['items'] = array_slice($order_items,($page-1)*$limit,$limit);
        
        $count = count($order_items);
        // $result['url'] = kernel::single('site_router')->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'return_order_items', 'arg' => array($order_id)));
        $product_data = array();
        foreach ($result['order']['items'] as $key => $product) {
            $item = array();
            $item['bn'] = $product['bn'];
            $item['name'] = $product['name'];
            $item['num'] = $product['quantity'];
            $product_data[] = $item;
        }
        $result['product_data'] = urlencode(json_encode($product_data));
        unset($result['orderlogs']);
        unset($result['order']);
        $result['reason'] = array(
            '协商一致退款','未按约定时间发货','虚假发货','其他'
            );
        return $this->apiData(true,$result,200);
    }

    public function dorefund($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $params['member_id'] = $member_id;
        if($params['edit'] == 'edit'){
            $rp = app::get('aftersales')->model('return_product');
            $obj_order = app::get('b2c')->model('orders');
            $rp->update(array('status'=>'13'),array('return_id'=>$params['return_id']));
            $obj_order->update(array('refund_status'=>'2'),array('order_id'=>$params['order_id']));
        }

        $obj_return_policy = kernel::service("aftersales.return_policy");
        $arr_settings = array();

        if (!isset($obj_return_policy) || !is_object($obj_return_policy))
        {
            return $this->apiData(false,null,400,app::get('aftersales')->_("售后服务应用不存在！"));
        }

        if (!$obj_return_policy->get_conf_data($arr_settings))
        {
            return $this->apiData(false,null,400,app::get('aftersales')->_("售后服务信息没有取到！"));
        }

        if(!$arr_settings['is_open_return_product'])
        {
            return $this->apiData(false,null,400,app::get('aftersales')->_("售后服务信息没有开启！"));
        }
        if(!empty($params['image_file'])){
            $img = kernel::single('openapi_utils_image')->getimgbyid($params['image_file']);
            if(empty($img)){
                return $this->apiData(false,null,400,app::get('b2c')->_('图片保存失败，请检查是否上传成功'));
            }
            $aData['image_file'] = $params['image_file'];
        }
        if(!empty($params['image_file1'])){
            $img = kernel::single('openapi_utils_image')->getimgbyid($params['image_file1']);
            if(empty($img)){
                return $this->apiData(false,null,400,app::get('b2c')->_('图片保存失败，请检查是否上传成功'));
            }
            $aData['image_file1'] = $params['image_file1'];
        }
        if(!empty($params['image_file2'])){
            $img = kernel::single('openapi_utils_image')->getimgbyid($params['image_file2']);
            if(empty($img)){
                return $this->apiData(false,null,400,app::get('b2c')->_('图片保存失败，请检查是否上传成功'));
            }
            $aData['image_file2'] = $params['image_file2'];
        }

        $obj_filter = kernel::single('b2c_site_filter');
        $_POST = $obj_filter->check_input($params);
        $product_data = json_decode(urldecode($params['product_data']),true);
        $objOrder = app::get('b2c')->model('orders');
        $store_id = $objOrder->getRow('store_id,score_u,payed',array('order_id'=>$_POST['order_id']));

        $sto= kernel::single("business_memberstore",$_POST['member_id']);
        $aData['store_id'] = $store_id['store_id'];
        $aData['order_id'] = $_POST['order_id'];
        $aData['add_time'] = time();
        //$aData['member_id'] = $this->member['member_id'];
        $aData['member_id'] = $_POST['member_id'];
        $aData['product_data'] = serialize($product_data);
        $aData['content'] = $_POST['content'];
        $aData['status'] = 1;

        $point_money_value = app::get('b2c')->getConf('site.point_deductible_value');
        if($_POST['gorefund_price'] > $store_id['payed']){
            $amount = $store_id['payed'];
            if($point_money_value != 0){
                $return_score = floor(($_POST['gorefund_price']-$store_id['payed'])/$point_money_value);
            }
            $score_u = $store_id['score_u'] - $return_score;
        }else{
            $amount = $_POST['gorefund_price'];
        }

        $aData['amount'] = $amount;
        $aData['return_score'] = $return_score;
        $aData['close_time'] = time()+86400*(app::get('b2c')->getConf('member.to_agree'));
        $aData['comment'] = $_POST['comment'];
        if($_POST['type']){
            $aData['refund_type'] = $_POST['type'];
        }
        if($_POST['edit'] == 'edit'){
            $aData['old_return_id'] = $_POST['return_id'];
        }
        $msg = "";
        $obj_aftersales = kernel::service("api.aftersales.request");
        //echo '<pre>';print_r($aData);exit;
        $_getParams = $params;
        $returnurl = $_getParams[0];
        if($returnurl == 'business')
        {
            $url = kernel::single('site_router')->gen_url(array('app' => 'business', 'ctl' => 'site_member', 'act' => 'refundstatus'));
        }
        else
        {
            $url = kernel::single('site_router')->gen_url(array('app' => 'aftersales', 'ctl' => 'site_member', 'act' => 'return_list'));

        }

        if ($obj_aftersales->generate($aData, $msg))
        {
            $obj_rpc_request_service = kernel::service('b2c.rpc.send.request');
            if ($obj_rpc_request_service && method_exists($obj_rpc_request_service, 'rpc_caller_request'))
            {
                if ($obj_rpc_request_service instanceof b2c_api_rpc_request_interface)
                    $obj_rpc_request_service->rpc_caller_request($aData,'aftersales');
            }
            else
            {
                $obj_aftersales->rpc_caller_request($aData);
            }
            //停止确认收货时间
            $confirm_time = $objOrder->getRow('confirm_time,status',array('order_id'=>$_POST['order_id']));
            if($confirm_time['confirm_time']){
                $time = $confirm_time['confirm_time'] - time();
            }else{
                $time = $confirm_time['confirm_time'];
            }
            //修改订单状态
            if($_POST['edit'] == 'edit' || $confirm_time['status'] == 'finish'){
                $refund_status = array('refund_status'=>'1');
            }else{
                $refund_status = array('refund_status'=>'1','confirm_time'=>$time);
            }
            $rs = $objOrder->update($refund_status,array('order_id'=>$_POST['order_id']));
            if($rs){
                $storeinfo = app::get('business')->model('storemanger')->getRow('account_id',array('store_id'=>$store_id['store_id']));
                $hqstore_id = kernel::single('b2c_goods_store')->hqStoreId();
                $mdl_account = app::get('pam')->model('account');
                if(in_array($store_id['store_id'], $hqstore_id)){
                    $data['to_id'] = '1';
                    $data['msg_to'] = '管理员';
                }else{
                    $data['to_id'] = $storeinfo['account_id'];
                    $data['msg_to'] = $mdl_account->get_operactor_name($storeinfo['account_id']);
                }
                $data['subject'] = app::get('b2c')->_("退款申请");
                $data['comment'] = app::get('b2c')->_("订单号：".$_POST['order_id']."向你发起了退款申请，请及时处理");
                $data['has_sent'] = 'true';
                $data['deal_type'] = '0';
                $data['member_id'] = $member_id;
                $data['uname'] = $mdl_account->get_operactor_name($member_id);
                kernel::single('b2c_message_msg')->send($data);
                return $this->apiData(true,null,200,app::get('b2c')->_('提交成功！'));
            }else{
                return $this->apiData(false,null,400,app::get('b2c')->_('提交成功！更新订单状态失败！'));
            }
        }
        else
        {
            return $this->apiData(false,null,400,$msg);
        }
    }

    /**
     * 拆分商品接口
     * @param
     * @return
     * @author hmg
     **/
    function splitCombineGoods($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        if(empty($member_id)){
            return $this->apiData(false,null,301,app::get('b2c')->_('请登录'));
        }
        $store = app::get('business')->model('storemanger')->getRow('store_id',array('account_id'=>$member_id));
        if(isset($params['goods_id']) && isset($params['num'])){
            $res = kernel::single('b2c_api_basic_order')->splitCombineGoods($store['store_id'],$params['goods_id'],$params['num'],$err_msg);
            if($res){
                $result = app::get('b2c')->model('goods_store')->getRow('store,store_onsale,store_freeze',array('store_id'=>$store['store_id'],'goods_id'=>$params['goods_id']));
                return $this->apiData(true, $result, 200, $err_msg);
            }else{
                return $this->apiData(false,null,400,$err_msg);
            }
        }else{
            return $this->apiData(false,null,400,app::get('b2c')->_('参数异常'));
        }
    }

}